package tr.gen._3bit.java._2k1s.dao.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import tr.gen._3bit.java._2k1s.dao.model.Model;

/*
 * An abstract class to implement basic operations for an entity service easily. 
 */
@Transactional
public abstract class ServiceImpl<I extends Model> implements Service<I> {
	private EntityManager em;

	protected abstract Class<I> getPersistanceClass();

	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@SuppressWarnings("unchecked")
	public List<I> findAll() {
		Query query = getEntityManager().createQuery(
				"select n FROM " + getPersistanceClass().getName() + " n");
		return query.getResultList();
	}

	public void save(I entity) {
		if (entity.getId() == null) {
			// new
			getEntityManager().persist(entity);
		} else {
			// update
			getEntityManager().merge(entity);
		}
	}

	public void remove(Integer id) {
		I entity = find(id);
		if (entity != null) {
			getEntityManager().remove(entity);
		}
	}

	protected EntityManager getEntityManager() {
		return em;
	}

	@SuppressWarnings("unchecked")
	public I find(Integer id) {
		return (I) getEntityManager().find(getPersistanceClass(), id);
	}

}